<template>
  <div
    class="login-page flex flex-col items-center justify-start pt-[15vh] inset-0 bg-[linear-gradient(139deg,#8eb3fd_2%,#f0f8fa_42%)]">
    <div class="w-full px-6 max-w-md">
      <h2 class="text-center text-2xl font-bold mb-16 leading-9 tracking-tight text-gray-900">手机号登录</h2>

      <div class="mb-4 min-h-[60px]">
        <div class="relative">
          <input type="tel" v-model="phone" placeholder="请输入手机号" @input="validatePhone"
            :class="{ 'border-red-500': errors.phone }" class="w-full h-[44px] px-3 bg-white rounded focus:outline-none">
          <p v-if="errors.phone" class="absolute top-[48px] text-xs text-red-500 text-left pl-1">{{ errors.phone }}</p>
        </div>
      </div>

      <div class="relative mb-8 min-h-[60px]">
        <div class="relative">
          <input type="text" v-model="verifyCode" placeholder="请输入验证码" @input="validateVerifyCode"
            :class="{ 'border-red-500': errors.verifyCode }"
            class="w-full h-[44px] px-3 bg-white rounded focus:outline-none">
          <button
            class="absolute right-3 top-1/2 -translate-y-1/2 text-sm font-normal outline-none border-none appearance-none select-none"
            :class="[cooldown > 0 ? 'text-gray-400' : 'text-[#2970FF]']" @click="handleGetVerifyCode"
            :disabled="cooldown > 0" style="-webkit-tap-highlight-color: transparent;">
            {{ cooldown > 0 ? `${cooldown}s` : '获取验证码' }}
          </button>
          <p v-if="errors.verifyCode" class="absolute top-[48px] text-xs text-red-500 text-left pl-1">{{
            errors.verifyCode }}</p>
        </div>
      </div>

      <button class="w-full h-[44px] rounded mt-4 text-base font-normal transition-colors duration-300"
        :class="[isFormValid ? 'bg-[#2970FF] text-white' : 'bg-[#E9ECEF] text-gray-500']" @click="handleLogin">
        登录/注册
      </button>
    </div>

    <!-- 在登录按钮下方添加分割线和微信登录按钮 -->
    <!-- <div class="w-full px-6 max-w-md mt-8">
      <div class="flex items-center justify-center">
        <div class="h-[1px] bg-gray-300 flex-1"></div>
        <span class="mx-4 text-sm text-gray-400">或</span>
        <div class="h-[1px] bg-gray-300 flex-1"></div>
      </div>

      <button class="w-full h-[44px] mt-8 rounded flex items-center justify-center bg-[#07C160] text-white"
        @click="handleWechatLogin">
        <img src="@/assets/images/wechat.png" alt="微信" class="w-6 h-6 mr-2">
        微信一键登录
      </button>
    </div> -->

    <div class="mt-4 text-xs text-gray-400 flex items-center justify-center">
      <input type="checkbox" v-model="agreePolicy" class="mr-1 h-3 w-3">
      <span>我已阅读并同意</span>
      <a href="#" class="text-blue-500 mx-1">隐私政策</a>
      <span>和</span>
      <a href="#" class="text-blue-500 ml-1">使用条款</a>
    </div>
  </div>

  <!-- 添加弹窗组件 -->
  <div v-if="showDialog" class="fixed inset-0 flex items-center justify-center z-50">
    <div class="fixed inset-0 bg-black opacity-50"></div>
    <div class="bg-white rounded-lg p-6 z-10 w-[80%] max-w-sm">
      <p class="text-center mb-6">请先同意用户协议和隐私政策</p>
      <button class="w-full h-[44px] bg-[#2970FF] text-white rounded" @click="showDialog = false">
        确定
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'  // 添加路由导入
import wxService from '@/utils/wxService'

const router = useRouter()  // 获取路由实
const phone = ref('')
const verifyCode = ref('')
const agreePolicy = ref(false)
const cooldown = ref(0)
const isPhoneValid = ref(false)
const errors = ref({
  phone: '',
  verifyCode: ''
})

const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/
  isPhoneValid.value = phoneRegex.test(phone.value)
  errors.value.phone = ''
}

const showDialog = ref(false)

const validateForm = () => {
  let isValid = true
  errors.value.phone = ''
  errors.value.verifyCode = ''

  if (!phone.value) {
    errors.value.phone = '请输入手机号'
    isValid = false
  } else if (!isPhoneValid.value) {
    errors.value.phone = '请输入正确的手机号'
    isValid = false
  }

  if (!verifyCode.value) {
    errors.value.verifyCode = '请输入验证码'
    isValid = false
  } else if (verifyCode.value.length < 4) {
    errors.value.verifyCode = '验证码格式不正确'
    isValid = false
  }

  if (!isValid) {
    return isValid
  }

  if (!agreePolicy.value) {
    showDialog.value = true
    isValid = false
  }

  return isValid
}

const validateVerifyCode = () => {
  errors.value.verifyCode = ''
  if (verifyCode.value.length > 0 && verifyCode.value.length < 4) {
    errors.value.verifyCode = '验证码格式不正确'
  }
}

const handleLogin = () => {
  if (!validateForm()) return
  // 登录逻辑
  router.push('/mobile/home')
}

const isFormValid = computed(() => {
  return isPhoneValid.value && verifyCode.value.length >= 4 && agreePolicy.value
})

const handleGetVerifyCode = () => {
  if (!phone.value) {
    errors.value.phone = '请输入手机号'
    return
  }
  if (!isPhoneValid.value) {
    errors.value.phone = '请输入正确的手机号'
    return
  }
  getVerifyCode()
}

const getVerifyCode = () => {
  if (cooldown.value > 0) return
  cooldown.value = 60
  const timer = setInterval(() => {
    cooldown.value--
    if (cooldown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
  // 这里可以添加发送验证码的接口调用
  console.log('发送验证码到手机号：', phone.value)

  // try {
  //       await userApi.updateUserInfo(form.value)
  //       ElMessage({
  //           message: '保存成功',
  //           type: 'success',
  //           duration: 1500,
  //           center: true
  //       })
  //       setTimeout(() => {
  //           router.push('/mobile/profile')
  //       }, 1500)
  //   } catch (error) {
  //       console.error('更新用户信息失败:', error)
  //   }
}

const handleWechatLogin = async () => {
  if (!agreePolicy.value) {
    showDialog.value = true
    return
  }

  return       router.push('/mobile/home')

  try {
    const res = await wxService.login()
    if (res.code) {
      // 调用后端接口，用code换取用户信息
      // const result = await userApi.wechatLogin(res.code)
      router.push('/mobile/home')
    }
  } catch (error) {
    console.error('微信登录失败:', error)
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  width: 100%;
  position: fixed;
  overflow-y: auto;
}

input {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border: 1px solid transparent;
  -webkit-tap-highlight-color: transparent;
  user-select: none;
}

input:focus {
  outline: none;
  -webkit-tap-highlight-color: transparent;
}

input.border-red-500 {
  border-color: #ef4444;
}

input::placeholder {
  color: #999;
  font-size: 14px;
}

button:disabled {
  opacity: 0.6;
}

.relative {
  position: relative;
}

.absolute {
  position: absolute;
}
</style>